import time
import devices
import config
import lvgl as lv
import utils
import fonts


class BootWidgets:
    def __init__(self):
        self.scr = lv.obj()
        self.scr.set_style_bg_color(lv.color_hex(0x000000), lv.PART.MAIN | lv.STATE.DEFAULT)

        self.logo = lv.img(self.scr)
        self.logo.set_size(240, 180)
        self.logo.set_pos(0, 0)

        img = utils.read_image(f'/resource/bootloader_bg.png')
        self.logo.set_src(img)

        self.load_bar = lv.bar(self.scr)
        self.load_bar.set_size(200, 10)
        self.load_bar.set_pos(20, 185)

        self.label = lv.label(self.scr)
        self.label.set_pos(22, 210)
        self.label.set_text("booting ...")
        lv.scr_load(self.scr)

    def connect_network(self):
        self.label.set_text("连接网络 ...")
        # 扫面网络
        devices.scan_wifi()
        flag = False
        self.load_bar.set_value(30, lv.ANIM.OFF)
        # 如果有WIFI配置就尝试连接
        if config.WIFI_NAME is not None and config.WIFI_NAME != "":
            for i in range(1, 4):
                self.label.set_text(f"第{i}次连接")
                try:
                    wlan = devices.connect_wifi(config.WIFI_NAME, config.WIFI_PWD)
                    flag = wlan.isconnected()
                    if flag:
                        break
                except Exception as err:
                    print(err)

        if flag:
            self.load_bar.set_value(40, lv.ANIM.OFF)
            self.label.set_text("同步时间...")
            devices.sync_ntp()
            if utils.is_birthday():
                img = utils.read_image(f'/resource/bootloader_bg_birthday.png')
                self.logo.set_src(img)
                time.sleep(3)
            self.load_bar.set_value(50, lv.ANIM.OFF)
            self.label.set_text("初始化系统中...")
            self.load_bar.set_value(60, lv.ANIM.OFF)
        else:
            # 没有或连接失败则开启AP配网模式
            import web
            ap = devices.create_wifi(config.AP_NAME, config.AP_PWD)
            scr = lv.obj()
            scr.set_style_bg_color(lv.color_hex(0x000000), lv.PART.MAIN | lv.STATE.DEFAULT)

            label_title = lv.label(scr)
            label_title.set_text("请连接设备热点后，使用手机浏览器扫码进行设备配网")
            label_title.set_style_text_font(fonts.font_cn_20, 0)
            label_title.set_long_mode(lv.label.LONG.SCROLL_CIRCULAR)
            label_title.set_size(220, 22)
            label_title.set_pos(10, 2)

            qr = lv.qrcode(scr, 160, lv.color_hex(0x000000), lv.color_hex(0xFFFFFF))
            data = f"WIFI:T:WPA;S:{config.AP_NAME};P:{config.AP_PWD if config.AP_PWD else ''};;"
            qr.update(data, len(data))
            qr.set_pos(40, 30)

            lv.scr_load(scr)

            label1 = lv.label(scr)
            label1.set_text(f"WIFI：{config.AP_NAME}")
            label1.set_style_text_font(fonts.font_cn_20, 0)
            label1.set_long_mode(lv.label.LONG.SCROLL_CIRCULAR)
            label1.set_size(220, 22)
            label1.set_pos(10, 196)

            label2 = lv.label(scr)
            if config.AP_PWD is None:
                label2.set_text(f"密码：无")
            else:
                label2.set_text(f"密码：{config.AP_PWD}")
            label2.set_style_text_font(fonts.font_cn_20, 0)
            label2.set_size(220, 22)
            label2.set_pos(10, 216)

            while not ap.isconnected():
                pass

            data = "http://" + ap.ifconfig()[0]

            label_title.set_text("请连接设备热点后，使用手机浏览器扫码进行设备配网，或访问" + data)
            qr.update(data, len(data))

            web.mws2.StartManaged()

    def start(self):
        self.load_bar.set_value(10, lv.ANIM.OFF)
        self.label.set_text("loading font...")
        # 延迟加载字体文件
        fonts.load_all()
        self.load_bar.set_value(20, lv.ANIM.OFF)
        self.label.set_style_text_font(fonts.font_cn_20, 0)
        self.connect_network()

        self.load_bar.set_value(80, lv.ANIM.OFF)
        self.label.set_text("启动WEB服务...")
        import web
        web.mws2.StartManaged()

        self.label.set_text("初始完毕，进入主界面...")
